package com.ibeeking.found.org.b.rest.service.impl;

import com.ibeeking.found.common.constants.WxCpServiceTypeConstant;
import com.ibeeking.found.common.entity.open.*;
import com.ibeeking.found.common.enums.OpenApiConfigEnum;
import com.ibeeking.found.common.enums.WxCpAppTypeEnum;
import com.ibeeking.gmc.global.api.feign.GlobalOpenFeignClient;
import com.ibeeking.found.org.b.rest.config.prop.RedisProperties;
import com.ibeeking.found.org.b.rest.service.IWxOpenService;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.redis.utils.RedisUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpJedisConfigImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 禁止在此类加其他业务方法
 *
 * @ClassName WxMpService
 * @Description
 * @Author ibeeking
 * @Date 2020-12-30 10:29
 **/
@Service
@EnableConfigurationProperties({RedisProperties.class})
public class WxOpenServiceImpl implements IWxOpenService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    //30分钟
    private static final Long TIME = 30 * 60 *1000L;

    @Resource
    private RedisUtils redisUtils;

    @Autowired
    private RedisProperties redisProperties;

    @Resource
    private GlobalOpenFeignClient globalOpenFeignClient;

    private OpenConfigDTO queryWxOpenConfigByType(Integer configType, Integer configSubType) {
        OpenConfigQuery query = new OpenConfigQuery();
        query.setType(configType);
        query.setSubType(configSubType);
        ResponseResult<OpenConfigDTO> responseResult = globalOpenFeignClient.queryOpenConfigOne(query);
        return responseResult.getData();
    }

    private OpenAuthDTO queryWxOpenAuthByTenantId(Long tenantId, Integer configType, Integer configSubType, Integer appType) {
        OpenAuthQuery query = new OpenAuthQuery();
        query.setTenantId(tenantId);
        query.setConfigType(configType);
        query.setConfigSubType(configSubType);
        query.setAppType(appType);
        ResponseResult<OpenAuthDTO> responseResult = globalOpenFeignClient.queryOpenAuthOne(query);
        return responseResult.getData();
    }

    /**
     * 获取公众号服务并将注册为bean
     *
     * @param
     * @return
     */
    @Override
    public WxCpService getWxCpService(Long tenantId) {
        try {
            OpenConfigDTO wxOpenConfigDTO = queryWxOpenConfigByType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_SB.getCode());
            if(wxOpenConfigDTO==null)  throw new BusinessException("企业微信自建应用OpenConfigDTO没有配置，请先配置!");

            OpenAuthDTO  wxOpenAuthDTO = queryWxOpenAuthByTenantId(tenantId, OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_SB.getCode(), WxCpServiceTypeConstant.CP_TYPE_SB);
            if(wxOpenAuthDTO == null) throw new BusinessException("企业微信自建应用OpenAuthDTO没有配置，请先配置!");
            WxCpService wxcCpService = SpringBeanUtil.getBean(WxCpService.class);
            if(wxcCpService == null) throw new BusinessException("get WxOpenService service error!");
            WxCpConfigStorage wxCpConfigStorage = getWxCpRedissonConfigStorage(tenantId, wxOpenConfigDTO, wxOpenAuthDTO);
            LogUtils.info(">>>>>>>>>>>>>自建应用ConfigStorage:{}", JsonUtils.toJsonStr(wxCpConfigStorage));

            wxcCpService.setWxCpConfigStorage(wxCpConfigStorage);
            wxcCpService.getAccessToken(true);
            return wxcCpService;
        }catch(Exception ex){
            LogUtils.error(ex.toString());
            return null;
        }
    }

    private WxCpConfigStorage getWxCpRedissonConfigStorage(Long tenantId, OpenConfigDTO wxOpenConfigDTO, OpenAuthDTO wxOpenAuthDTO) {
        OpenAuthOfExtend openAuthOfExtend = wxOpenAuthDTO.getOpenAuthOfExtend();
        if(openAuthOfExtend == null) throw new BusinessException("企业微信自建应用没有配置，请先配置!");
        OpenAuthOfWxCpSb  openAuthOfWxCpSb = openAuthOfExtend.getOpenAuthOfWxCpSb();
        WxCpJedisConfigImpl wxCpJedisConfigImpl = new WxCpJedisConfigImpl(redisProperties.getJedisPool(), "wx:cp:sb:".concat(tenantId.toString()));

        wxCpJedisConfigImpl.setCorpId(wxOpenAuthDTO.getOpenAppId());
        wxCpJedisConfigImpl.setCorpSecret(wxOpenAuthDTO.getAppSecret());
        wxCpJedisConfigImpl.setToken(wxOpenAuthDTO.getAppToken());
        wxCpJedisConfigImpl.setAesKey(wxOpenAuthDTO.getAppAesKey());
        OpenConfigOfExtend openConfigOfExtend = wxOpenConfigDTO!=null?wxOpenConfigDTO.getOpenConfigOfExtend():null;
        OpenConfigOfWxCp openConfigOfWxCp = openConfigOfExtend!=null?openConfigOfExtend.getOpenConfigOfWxCp():null;
        OpenConfigOfWxCpTalkData openConfigOfWxCpTalkData = openConfigOfWxCp!=null?openConfigOfWxCp.getWxCpTalkData():null;
        if(openConfigOfWxCpTalkData!=null) {
            wxCpJedisConfigImpl.setMsgAuditSecret(openConfigOfWxCpTalkData.getTalkDataSecret());
            wxCpJedisConfigImpl.setMsgAuditPriKey(openConfigOfWxCpTalkData.getTalkDataPriKey());
            wxCpJedisConfigImpl.setMsgAuditLibPath(openConfigOfWxCpTalkData.getTalkDataLibPath());
        }
        if(StringUtils.isNotEmpty(wxOpenAuthDTO.getAppId())) {
            Integer agentId  = Integer.parseInt(wxOpenAuthDTO.getAppId());
            wxCpJedisConfigImpl.setAgentId(agentId);
        }
        if(StringUtils.isNotEmpty(openAuthOfWxCpSb.getAccessToken())){
            WxAccessToken wxAccessToken = new WxAccessToken();
            wxAccessToken.setAccessToken(openAuthOfWxCpSb.getAccessToken());
            wxAccessToken.setExpiresIn(openAuthOfWxCpSb.getAccessTokenExpiresTime());
            wxCpJedisConfigImpl.updateAccessToken(wxAccessToken);
        }
        return wxCpJedisConfigImpl;
    }

    private WxOpenServiceImpl getBean() {
        return SpringBeanUtil.getBean(this.getClass());
    }
}